package com.example.demo.mybatis;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Data
public class Student {

    private Integer id;

    private String name;

    private Attrs attrs;

    @Data
    public static class Attrs {
        private String age;
    }

    public static class AttrsTypeHandler implements TypeHandler<Attrs> {

        @Override
        public void setParameter(PreparedStatement preparedStatement, int i, Attrs s, JdbcType jdbcType) throws SQLException {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                preparedStatement.setString(i, objectMapper.writeValueAsString(s));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public Attrs getResult(ResultSet resultSet, String s) throws SQLException {
            String result = resultSet.getString(s);

            ObjectMapper objectMapper = new ObjectMapper();
            try {
                return objectMapper.readValue(result, Attrs.class);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public Attrs getResult(ResultSet resultSet, int i) throws SQLException {
            String result = resultSet.getString(i);
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                return objectMapper.readValue(result, Attrs.class);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public Attrs getResult(CallableStatement callableStatement, int i) throws SQLException {
            String result = callableStatement.getString(i);
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                return objectMapper.readValue(result, Attrs.class);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}
